package com.ruoyi.function.utility;


import com.ruoyi.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class MiniAppTokenService {
    
    private static final Logger log = LoggerFactory.getLogger(MiniAppTokenService.class);
    
    @Autowired
    private RedisCache redisCache;
    
//    @Autowired
//    private TechnicianInfoMapper technicianInfoMapper;
//
//    @Autowired
//    private GarageInfoMapper garageInfoMapper;
    
    private static final String USER_APP_TOKEN = "user_token:";    // 用户端token
    private static final String PROVIDER_APP_TOKEN = "provider_token:"; // 服务商端token
    private static final Integer TOKEN_EXPIRE_HOURS = 72;
    
//    /**
//     * 创建token并返回完整的登录信息
//     */
//    public Map<String, Object> createTokenInfo(UserInfo userInfo) {
//        String token = UUID.randomUUID().toString();
//
//        Map<String, Object> loginUser = new HashMap<>();
//        loginUser.put("userId", userInfo.getUserId());
//        loginUser.put("mobile", userInfo.getMobile());
//        loginUser.put("userType", userInfo.getUserType());
//        loginUser.put("realName", userInfo.getRealName());
//        loginUser.put("realNameAuthStatus", userInfo.getRealNameAuthStatus());
//        loginUser.put("roleTypes", userInfo.getRoleTypes());
//        loginUser.put("currentRole", userInfo.getCurrentRole());
//        loginUser.put("nickname", userInfo.getNickname());
//        loginUser.put("avatar", userInfo.getAvatar());
//
//        redisCache.setCacheObject(getTokenKey(token), loginUser, TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
//
//        Map<String, Object> tokenInfo = new HashMap<>();
//        tokenInfo.put("token", token);
//        tokenInfo.put("userInfo", loginUser);
//
//        return tokenInfo;
//    }
    
//    /**
//     * 创建token - 统一处理服务商ID
//     */
//    public String createToken(UserInfo userInfo, String appType) {
//        String token = UUID.randomUUID().toString();
//        Map<String, Object> loginUser = new HashMap<>();
//
//        // 基础信息
//        loginUser.put("userId", userInfo.getUserId());
//        loginUser.put("mobile", userInfo.getMobile());
//        loginUser.put("userType", userInfo.getUserType());
//        loginUser.put("currentRole", userInfo.getCurrentRole());
//        loginUser.put("appType", appType);
//        loginUser.put("roleTypes", userInfo.getRoleTypes());
//
//        // 根据角色添加服务商ID
//        if (userInfo.getCurrentRole() == 2) { // 技师
//            TechnicianInfo techInfo = technicianInfoMapper.selectByUserId(userInfo.getUserId());
//            if (techInfo != null) {
//                loginUser.put("technicianId", techInfo.getTechnicianId());
//            }
//        } else if (userInfo.getCurrentRole() == 3) { // 商家
//            GarageInfo garageInfo = garageInfoMapper.selectByUserId(userInfo.getUserId());
//            if (garageInfo != null) {
//                loginUser.put("garageId", garageInfo.getGarageId());
//            }
//        }
//
//        // 存入Redis
//        String tokenKey = getTokenKey(token);
//        redisCache.setCacheObject(tokenKey, loginUser, TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
//
//        return token;
//    }
    
    public Map<String, Object> getLoginUser(String token) {
        if (!StringUtils.hasText(token)) {
            return null;
        }
        
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        // 检查是否使用了正确的key前缀
        String tokenKey = getTokenKey(token);
        Map<String, Object> loginUser = redisCache.getCacheObject(tokenKey);
        
        // 添加日志便于排查
        log.info("Token: {}, TokenKey: {}, LoginUser: {}", token, tokenKey, loginUser);
        
        return loginUser;
    }
    
    public void removeToken(String token) {
        // 去掉Bearer前缀
        if (token.startsWith("Bearer ")) {
            token = token.replace("Bearer ", "");
        }
        
        String key = USER_APP_TOKEN + token;
        redisCache.deleteObject(key);
        log.info("删除token: {}", token);
    }

    /**
     * 刷新token有效期
     */
    public void refreshToken(String token) {
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        String userKey = getTokenKey(token);
        Map<String, Object> loginUser = redisCache.getCacheObject(userKey);
        if (loginUser != null) {
            // 如果token剩余有效期小于24小时，则刷新有效期
            Long expireTime = redisCache.getExpire(userKey);
            if (expireTime != null && expireTime < TimeUnit.HOURS.toSeconds(24)) {
                redisCache.expire(userKey, TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
                
                // 同时刷新手机号对应的token记录
                String mobile = (String) loginUser.get("mobile");
                String appType = loginUser.get("appType").toString();
                String tokenKey = "PROVIDER_APP".equals(appType) ? 
                    PROVIDER_APP_TOKEN + mobile : 
                    USER_APP_TOKEN + mobile;
                redisCache.expire(tokenKey, TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
                
                log.info("刷新token有效期: {}", token);
            }
        }
    }

    /**
     * 刷新token - 保持服务商ID
     */
    public String refreshToken(String token, Map<String, Object> loginUser) {
        // 保留原有的服务商ID
        Map<String, Object> oldLoginUser = getLoginUser(token);
        if (oldLoginUser != null) {
            if (oldLoginUser.get("technicianId") != null) {
                loginUser.put("technicianId", oldLoginUser.get("technicianId"));
            }
            if (oldLoginUser.get("garageId") != null) {
                loginUser.put("garageId", oldLoginUser.get("garageId"));
            }
        }
        
        // 生成新token
        String newToken = UUID.randomUUID().toString();
        String userKey = getTokenKey(newToken);
        redisCache.setCacheObject(userKey, loginUser, TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
        
        // 删除旧token
        deleteLoginUser(token);
        
        return newToken;
    }

    public void deleteLoginUser(String token) {
        if (token != null) {
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            // 1. 获取用户信息
            Map<String, Object> loginUser = redisCache.getCacheObject(getTokenKey(token));
            if (loginUser != null) {
                String mobile = (String) loginUser.get("mobile");
                
                // 2. 删除手机号对应的token
                String userTokenKey = USER_APP_TOKEN + mobile;
                String providerTokenKey = PROVIDER_APP_TOKEN + mobile;
                redisCache.deleteObject(userTokenKey);
                redisCache.deleteObject(providerTokenKey);
            }
            
            // 3. 删除token对应的用户信息
            redisCache.deleteObject(getTokenKey(token));
        }
    }

    private String getTokenKey(String token) {
        // 先尝试获取当前token的信息
        String providerKey = PROVIDER_APP_TOKEN + token;
        String userKey = USER_APP_TOKEN + token;
        
        // 添加日志
        log.info("Checking token in provider key: {}", providerKey);
        Map<String, Object> providerInfo = redisCache.getCacheObject(providerKey);
        if (providerInfo != null) {
            return providerKey;
        }
        
        log.info("Checking token in user key: {}", userKey);
        Map<String, Object> userInfo = redisCache.getCacheObject(userKey);
        if (userInfo != null) {
            return userKey;
        }
        
        // 如果都没找到，默认返回服务商token key
        return providerKey;
    }

//    /**
//     * 创建用户端token
//     */
//    public String createUserToken(UserInfo userInfo) {
//        String token = UUID.randomUUID().toString();
//
//        // 只存储用户端需要的基本信息
//        Map<String, Object> loginUser = new HashMap<>();
//        loginUser.put("userId", userInfo.getUserId());
//        loginUser.put("mobile", userInfo.getMobile());
//        loginUser.put("userType", 0);  // 用户端固定为普通用户
//        loginUser.put("appType", "USER_APP");
//
//        // 将token信息存入Redis
//        String userKey = getUserTokenKey(token);
//        redisCache.setCacheObject(userKey, loginUser, TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
//
//        // 保存手机号和token的关系(用于单点登录)
//        String mobileKey = USER_APP_TOKEN + userInfo.getMobile();
//        redisCache.setCacheObject(mobileKey, token, TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
//
//        return token;
//    }
    
    /**
     * 获取用户登录信息
     */
    public Map<String, Object> getUserLoginInfo(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        String userKey = getUserTokenKey(token);
        Map<String, Object> loginUser = redisCache.getCacheObject(userKey);
        
        // 验证是否是用户端token
        if (loginUser != null && "USER_APP".equals(loginUser.get("appType"))) {
            return loginUser;
        }
        return null;
    }
    
    /**
     * 刷新用户token有效期
     */
    public void refreshUserToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        String userKey = getUserTokenKey(token);
        Map<String, Object> loginUser = redisCache.getCacheObject(userKey);
        
        if (loginUser != null && "USER_APP".equals(loginUser.get("appType"))) {
            // 如果token剩余有效期小于24小时，则刷新
            Long expireTime = redisCache.getExpire(userKey);
            if (expireTime != null && expireTime < TimeUnit.HOURS.toSeconds(24)) {
                // 刷新token有效期
                redisCache.expire(userKey, TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
                
                // 同时刷新手机号关联的token有效期
                String mobile = (String) loginUser.get("mobile");
                String mobileKey = USER_APP_TOKEN + mobile;
                redisCache.expire(mobileKey, TOKEN_EXPIRE_HOURS, TimeUnit.HOURS);
                
                log.info("刷新用户token有效期: {}", token);
            }
        }
    }
    
    /**
     * 删除用户token
     */
    public void deleteUserToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        String userKey = getUserTokenKey(token);
        Map<String, Object> loginUser = redisCache.getCacheObject(userKey);
        
        if (loginUser != null && "USER_APP".equals(loginUser.get("appType"))) {
            // 删除token
            redisCache.deleteObject(userKey);
            
            // 删除手机号关联的token
            String mobile = (String) loginUser.get("mobile");
            String mobileKey = USER_APP_TOKEN + mobile;
            redisCache.deleteObject(mobileKey);
            
            log.info("删除用户token: {}", token);
        }
    }
    
    private String getUserTokenKey(String token) {
        return USER_APP_TOKEN + token;
    }

    /**
     * 获取服务商ID的工具方法
     */
    public Long getProviderId(String token) {
        Map<String, Object> loginUser = getLoginUser(token);
        if (loginUser != null) {
            Object technicianId = loginUser.get("technicianId");
            if (technicianId != null) {
                return (Long) technicianId;
            }
            Object garageId = loginUser.get("garageId");
            if (garageId != null) {
                return (Long) garageId;
            }
        }
        return null;
    }
} 